/**
 * 处理菜单，后端权限文件
 */

import { pages } from "@/layout/menus";
import { ref } from "vue";
import type { RouteComponent } from "vue-router";
import router from '../router/index';
import { useCommonStore } from "@/stores/common";
import { findPath } from "@/utils/treeHelper";
import { useKeepLiveStore } from '../stores/keepLive';


export interface PagePermType {
  title: string;
  routeName: string;
  componentPath: string;
  meta: {
    cache: boolean;      // 如果设置为true，则不会被 <keep-alive> 缓存(默认 false)
    icon?: string;       // 设置该路由的图标，对应路径src/assets/icons/svg
    perm: boolean;  // 是否有跳转操作权限
    layout: boolean;  // 是否为全屏操作页面
    menu: boolean; // 是否是菜单
  },
  children?: PagePermType[]
}



// 页面组件文件
const components = import.meta.glob("../views/**/*.vue", { eager: true }) as Record<string, { default: RouteComponent }>



export function usePagePerm() {
  const permIsLoad = ref(false) // 权限是否已经加载
  const { sysPages, setSysPages } = useCommonStore()
  const keepLiveStore = useKeepLiveStore()

  // 加载router内容， 初始化页面内容
  function initPermPage() {
    const findRouterArray: string[] = [] // 存储已经找到组件的路由
    function findPage(pages: PagePermType[]): PagePermType | void {
      for (const page of pages) {
        if (findRouterArray.includes(page.routeName)) continue

        if (!page.meta.perm) { // 无权限直接过滤
          page.meta.menu = false // 无权限访问直接过滤页面
          continue
        }

        const isFind = components[`../views/${page.componentPath}.vue`] || components[`../views${page.componentPath}.vue`]
        
        // 没有找到对应页面组件跳过本次检查
        if (!isFind) {
          continue
        }

        if(page.children){
          findPage(page.children)
        }

        findRouterArray.push(page.routeName)

        // 路由添加位置
        const route = {
          path: page.componentPath.startsWith("/") ? page.componentPath : `/${page.componentPath}`,
          component: () => isFind.default,
          meta: page.meta,
          name: page.routeName,
        }
        
        page.meta.layout ? router.addRoute("layout", route) : router.addRoute(route)
        if(route.meta.cache) keepLiveStore.addKeepAlive(page.routeName)
      }
    }

    findPage(sysPages)

    if (import.meta.env.DEV)
      console.log(router.getRoutes())
  }


  function requestUserInfo(): Promise<PagePermType[]> {
    // 后端请求菜单权限，并加工完所有数据，返回菜单信息
    return new Promise((resolve, reject) => {
      resolve(pages)
    })
  }



  router.beforeEach((to, from, next) => {
    if (permIsLoad.value) {
      if (to.name == "404" && router.getRoutes().find(item => item.path === to.path)) { // 页面已经缓存，则重新加载
        next({ path: to.fullPath, replace: true })
        return
      }
      next()
    } else {
      requestUserInfo().then((data) => {
        setSysPages(data)
        initPermPage()
        permIsLoad.value = true
        next({ ...to, replace: true })
      }).catch(err => {
        next({ name: "login" })
      })
    }
  })

  return {
    initPermPage
  }
}


export function findPrantPage(pages: PagePermType[], routeName: string) {
  return findPath(pages, (node) => node.routeName === routeName)
}